
package com.example.previewvideo;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.example.demo.R;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//Camera2 预览录像测试类

public class Camera2PreviewVideoActivity extends Activity {
    private String TAG = "Camera2PreviewVideoActivity";


    private Camera mCamera;
    private SurfaceHolder mSurfaceHolder;
    int mScreenWidth;
    int mScreenHeight;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        mSurfaceHolder = surfaceView.getHolder();
        mSurfaceHolder.addCallback(surfaceCallback);

        findViewById(R.id.start_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startRecording();
            }
        });
        findViewById(R.id.end_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRecording();
            }
        });


        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
//            String[] cameraIds = cameraManager.getCameraIdList();
//            for (String id : cameraIds) {
//                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
//
//                StreamConfigurationMap configs = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
//                // 获取视频录制的格式尺寸列表
//                Size[] videoSizes = configs.getOutputSizes(MediaRecorder.class);
//
//                // 遍历支持的尺寸
//                for (Size size : videoSizes) {
//                    int width = size.getWidth();
//                    int height = size.getHeight();
//                    // 输出支持的分辨率
//                    LogUtils.i("获取支持的视频录制分辨率列表", "Supported Video Size: " + width + " x " + height);
//                }
//                // 获取支持的帧率范围列表
//                Range<Integer>[] fpsRanges = characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES);
//
//                // 遍历支持的帧率范围
//                for (Range<Integer> range : fpsRanges) {
//                    int minFps = range.getLower();
//                    int maxFps = range.getUpper();
//                    // 输出支持的帧率范围
//                    LogUtils.i("获取支持的帧率范围列表", "Supported FPS Range: " + minFps + " - " + maxFps);
//                }
//
//
////                int[] formats = characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_FORMATS);
////                for (int format : formats) {
////                    LogUtils.d(TAG, "Supported Format: " + format);
////                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // Open the camera here
            try {


                mCamera = Camera.open();


/**
 * 增加对聚焦模式的判断,没有它会很模糊
 // */
                Camera.Parameters parameters = mCamera.getParameters();

                // 获取支持的帧率范围列表
//                Camera.Parameters parameters = camera.getParameters();
//                List<int[]> supportedFpsRanges = parameters.getSupportedPreviewFpsRange();
//
//// 遍历支持的帧率范围
//                for (int[] range : supportedFpsRanges) {
//                    int minFps = range[0];
//                    int maxFps = range[1];
//                    // 输出支持的帧率范围
//                    LogUtils.i("获取支持的帧率范围列表", "Supported FPS Range: " + minFps + " - " + maxFps);
//                }


                List<String> focusModesList = parameters.getSupportedFocusModes();
                if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                }
                parameters.setRecordingHint(true);

                mCamera.setParameters(parameters);


                mCamera.setPreviewDisplay(holder);
                mCamera.setDisplayOrientation(0);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // Start the preview for the camera
            mCamera.startPreview();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // Release the camera resources
            if (mCamera != null) {
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }

        }
    };


    private int getDegree() {
        //获取当前屏幕旋转的角度
        int rotating = this.getWindowManager().getDefaultDisplay().getRotation();
        int degree = 0;//度数
        //根据手机旋转的角度，来设置surfaceView的显示的角度
        switch (rotating) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }


    /**
     * 释放摄像头资源
     */
    private void releaseCameraResource() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.lock();
            mCamera.release();
            mCamera = null;
        }
    }


    private MediaRecorder mMediaRecorder;
    private boolean isRecording = false;

    int VideoSizeWidth = 1920;//4160x3120
    int VideoSizeHeight = 1080;
    int fps = 30;

    //    int bitRate = 100 * 1000000;// 100 Mbps
    int bitRate = 10000000;//  Mbps

    int recordTime = 10 * 1000;//秒

    private void startRecording() {

        Camera.Parameters parameters = mCamera.getParameters();
//        List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
//        for (int i = 0; i < previewSizeList.size(); i++) {
//            Camera.Size size = previewSizeList.get(i);
//            LogUtils.i("PREVIEW_SIZE", String.format("camera preview width=%d,height=%d", size.width, size.height));
//        }


//        parameters.setPictureSize(VideoSizeWidth, VideoSizeHeight);
        mCamera.setParameters(parameters);


        LogUtils.i(TAG, "startRecording");
        mCamera.unlock();
        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setCamera(mCamera);

//        try {
//            MediaCodec codec = MediaCodec.createByCodecName("OMX.google.h264.encoder");
//            MediaFormat format = MediaFormat.createVideoFormat("video/avc", 1280, 720);
//            format.setInteger(MediaFormat.KEY_BIT_RATE, 1000000);
//            format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
//            format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
//            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
//            format.setInteger(MediaFormat.KEY_COMPLEXITY, 3); // 设置压缩级别为 medium
//
//            codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
//
//        } catch (Exception e) {
//        }


        //设置录音的音频编码比特率
//        mMediaRecorder.setAudioEncodingBitRate();

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//
        // 设置要用于录制的音频源。
//        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//        // 设置要用于录制的视频源。
//        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
//        // 设置录制期间生成的输出文件的格式。
//        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

        // 设置要捕获的视频的帧速率。
        mMediaRecorder.setVideoFrameRate(fps);
        mMediaRecorder.setVideoSize(VideoSizeWidth, VideoSizeHeight);
        // 设置要用于录制的视频编码器。
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        // 设置要用于录制的音频编码器。
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
//        mMediaRecorder.setAudioSamplingRate(44); // 设置音频采样率为44
//        mMediaRecorder.setAudioEncodingBitRate(64); // 设置音频比特率为64

        //设置录制视频编码比特率 10000000

        mMediaRecorder.setVideoEncodingBitRate(bitRate);
//        mMediaRecorder.setVideoEncodingBitRate();

//        mMediaRecorder.setVideoEncodingProfileLevel();

//        mMediaRecorder.setVideoEncodingProfileLevel(MediaRecorder.VideoEncoder.H264, MediaRecorder.VideoEncoder.DEFAULT, MediaCodecInfo.CodecProfileLevel.AVCProfileHigh);

//        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));


        LogUtils.i(TAG, "startRecordingFile: " + getOutputMediaFile().toString() + "  bitRate:" + bitRate + "  :" + CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));


        // 生成MP4文件路径
        mMediaRecorder.setOutputFile(getOutputMediaFile());
        try {
            mMediaRecorder.prepare();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        mMediaRecorder.start();
        isRecording = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                stopRecording();
            }
        }, recordTime);
    }

    private void stopRecording() {


        LogUtils.i(TAG, "stopRecording: ");

        if (isRecording && mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            mCamera.lock();
            isRecording = false;

        }
    }


    String videoPath;

    private String getOutputMediaFile() {
        String directoryPath = getCacheDir().getAbsolutePath() + "/videoName/";

        File mediaStorageDir = new File(directoryPath);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());


        videoPath = new File(mediaStorageDir.getPath() + File.separator +
                "VID_" + timeStamp + "_" + VideoSizeWidth + "_" + VideoSizeHeight + "_" + fps + "_" + bitRate + "__" + Build.MODEL + ".mp4").getPath();

        return videoPath;
//        return new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + "_" + VideoSizeWidth + "_" + VideoSizeHeight + "_" + fps + "_" + bitRate + "__" + Build.MODEL + ".mp4");
    }


}
